package com.yancloud.android.contractclient;

import java.math.BigInteger;

import crypto.SM2;
import crypto.SM2KeyPair;


public abstract class SM2Verifible {
	public abstract String getPublicKey();

	public abstract String getContentStr();

	public abstract void setPublicKey(String pubkey);

	public String signature;

	public void doSignature(String privateKey) {
		SM2 sm2 = new SM2();
		BigInteger privkey = new BigInteger(privateKey, 16);
		doSignature(new SM2KeyPair(sm2.getPubkeyByPrivkeyKey(privkey), privkey));
	}

	public void doSignature(SM2KeyPair pair) {
		SM2 sm2 = new SM2();
		setPublicKey(pair.getPublicKeyStr());
		signature = sm2.sign(getContentStr().getBytes(), pair.getPrivateKey().toString(16)).toString();
	}

	public boolean verifySignature() {
		try {
			SM2 sm2 = new SM2();
			String verifiedStr = getContentStr();
			return sm2.verify(verifiedStr, SM2.Signature.loadFromString(signature), "",
					SM2.importPublicKey(hexStr2Byte(getPublicKey())));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public void setSignature(String signature) {
		this.signature = signature;
	}

	public static int char2Int(char c) {
		int ret = c;
		if (c >= 'a' && c <= 'f') {
			ret = '0' + 10 + c - 'a';
		}
		ret = ret - '0';
		if (ret >= 0 && ret < 16) {
			return ret;
		} else
			throw new IllegalArgumentException("the input should be 0-9 and a-f, but received " + c);
	}

	public static byte[] hexStr2Byte(String str) {
		byte[] ret = new byte[str.length() / 2];
		for (int i = 0; i < str.length() / 2; i++) {
			int val = (char2Int(str.charAt(i * 2)) << 4) + (char2Int(str.charAt(i * 2 + 1)));
			ret[i] = (byte) (val & 0xff);
		}
		return ret;
	}
}
